package com.team.six.bluecatshop.controller;

import com.team.six.bluecatshop.domain.Activity;
import com.team.six.bluecatshop.domain.Product;
import com.team.six.bluecatshop.domain.Sku;
import com.team.six.bluecatshop.service.ActivityService;
import com.team.six.bluecatshop.service.ProductService;
import com.team.six.bluecatshop.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@RequestMapping("/activity")
@Controller
public class ActivityController {
    @Autowired
    ActivityService activityService;
    @Autowired
    ProductService productService;
    @Autowired
    SkuService skuService;

    /**
     * 跳转限时购列表
     * */
    @RequestMapping("/time-buy-list")
    public String timeBuy(Model model){
        List<Activity> activities = activityService.findAll();
        for (Activity a:activities){
            Product product = productService.findById(a.getProductId());
            product=productService.setImgToProduct(product);
            a.setProduct(product);
        }
        model.addAttribute("activities",activities);
        return "rushToBuyList";
    }
    /**
     * 限时购商品细节
     * */
    @GetMapping("/time-buy-details")
    public String timeBuyDetails(String activityId, String productId, Model model){

        Activity activity = activityService.findById(activityId);
        Product product=productService.findById(productId);//根据传来的id找到对应商品
        List<Sku> skus = skuService.findSkuByProductId(productId);//加载商品的规格
        product.setSkus(skus);//将sku放入商品中暂存
        activity.setProduct(product);
        model.addAttribute("activity",activity);

        return "rushToBuyDetails.html";
    }



    @RequestMapping("/activityDelete")
    @ResponseBody
    public String activityDelete(String activityId){

        Activity activity = activityService.findById(activityId);
        Date timeEnd = activity.getTimeEnd();
        Date nowTime = new Date();

        /*格式化时间类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss") ; //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(timeEnd); //可以把日期转换转指定格式的字符串
        String now =dateFormat.format(nowTime);
        System.out.println(now);
        */
        if(nowTime.after(timeEnd)){
            activityService.remove(activityId);
        }
        return "success";
    }
}
